package leecode

func longestSubarray(nums []int, limit int) int {
	hashMap := make(map[int]int) //记录数组中的元素, 以及出现的次数
	left := 0
	var result int
	for right, num := range nums {
		hashMap[num]++
		for {
			maxNum, minNum := num, num
			for n, _ := range hashMap {
				maxNum = max(maxNum, n)
				minNum = min(minNum, n)
			}
			if maxNum-minNum <= limit {
				break
			}
			if hashMap[nums[left]]--; hashMap[nums[left]] <= 0 {
				delete(hashMap, nums[left])
			}
			left++
		}
		result = max(result, right-left+1)
	}
	return result
}
